<?php

namespace app\middleware;

use app\admin\service\ActionLogService;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use support\Container;

class ActionLog implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        // 记录开始时间
        $startTime = microtime(true);
        // 执行下一个中间件或控制器方法
        $response = $handler($request);
        // 计算执行时间
        $executionTime = round((microtime(true) - $startTime) * 1000);
        // 异步记录日志
        $this->recordLog($request, $response, $executionTime);
        return $response;
    }

    /**
     * 记录日志
     * @param Request $request
     * @param Response $response
     * @param int $executionTime
     * @return void
     */
    private function recordLog(Request $request, Response $response, int $executionTime): void
    {
        try {
            $admin = $request->admin ?? null;
            if (!$admin) {
                return;
            }
            // 获取响应数据
            $responseData = json_decode($response->rawBody(), true) ?: [];
            // 记录日志
            $actionLogService = Container::get(ActionLogService::class);
            $actionLogService->record($request, $admin, $response->getStatusCode() == 200, $responseData, $executionTime);
        } catch (\Throwable $e) {
            // 避免日志记录异常影响主流程
            // 可以在这里记录错误日志用于调试
        }
    }
}